<template>
  <el-dialog
    title="合作伙伴编辑"
    v-model="visible"
    top="10vh"
    width="600px"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataFormRules"
      label-position="right"
      label-width="120px"
      v-loading="loading"
    >
      <el-form-item label="合作伙伴名称" prop="partnerName">
        <el-input v-model="dataForm.partnerName"></el-input>
      </el-form-item>
      <el-form-item label="LOGO" prop="logo">
        <el-avatar :src="showLogo" style="cursor: pointer" @click="avatarClickEvent"></el-avatar>
      </el-form-item>
      <el-form-item label="合作伙伴联系人" prop="partnerUserName">
        <el-input v-model="dataForm.partnerUserName" placeholder="请输入联系人名称"></el-input>
      </el-form-item>
      <el-form-item label="合作伙伴手机号" prop="partnerPhone">
        <el-input v-model="dataForm.partnerPhone" placeholder="请输入手机号"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="updateOrCreate">确定</el-button>
    </template>

    <!-- logo编辑 -->
    <AvatarCropper v-model="showAvatarCropper" :avatar-url="dataForm.logo" @change="uploadSuccess"></AvatarCropper>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, type PropType } from 'vue'
import { UPDATE_MODEL_EVENT } from 'cm/contants'

import AvatarCropper from './AvatarCropper.vue'

import { validPhone } from '@/utils/validate'

import { createPartner, getPartnerInfo, updatePartner, type ICreateOrUpdatePanter } from '@/api/partner'
import { ElMessage } from 'element-plus'
import appConfig from '@/config/index'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
    default: false
  },
  currId: {
    type: String,
    required: true,
    default: ''
  },
})

const emit = defineEmits([UPDATE_MODEL_EVENT, 'change'])

const visible = ref<boolean>(false)

const handleClose = () => {
  emit(UPDATE_MODEL_EVENT, false)
}

const defaultForm = {
  id: '',
  partnerName: '',
  partnerPhone: '',
  partnerUserName: '',
  logo: ''
}
// 表单逻辑
const dataForm = ref<ICreateOrUpdatePanter>({ ...defaultForm })

const validPhoneNum = (rule: any, value: string, callback: any) => {
  if (validPhone(value)) {
    callback()
  } else {
    callback(new Error('请输入正确的手机号'))
  }
}

const dataFormRules = {
  partnerName: [{ required: true, message: '请输入合作伙伴名称', trigger: 'blur' }],
  partnerPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validPhoneNum, trigger: 'blur' }
  ],
  partnerUserName: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
  ]
}
const loading = ref<boolean>(false)
// 查询合作伙伴详情
const getPartnerInfoApi = async (currId: string) => {
  loading.value = true
  const res = await getPartnerInfo(currId)
  loading.value = false
  if (res?.code === 200) {
    dataForm.value = res.data as ICreateOrUpdatePanter;
    showLogo.value = `${appConfig.api.staticUrl}${dataForm.value.logo}`
    console.log()
  }
}

// 头像编辑
const showAvatarCropper = ref<boolean>(false)
const avatarClickEvent = () => {
  showAvatarCropper.value = !showAvatarCropper.value
}
const showLogo = ref('');
const uploadSuccess = (url: string) => {
  dataForm.value.logo = url
  showLogo.value = `${appConfig.api.staticUrl}${url}`
}

watch(
  () => props.modelValue,
  async () => {
    visible.value = props.modelValue
    if (props.modelValue && props.currId) {
      await getPartnerInfoApi(props.currId)
    }
  }
)

const dataFormRef = ref()
const updateOrCreate = async () => {
  dataFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      const res = await updatePartner(dataForm.value)
      loading.value = false
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '更新成功' })
        emit('change')
        handleClose()
      } else {
        ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试！' })
      }
    }
  })
}
</script>
